package com.fagertveit.chainsawrus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.fagertveit.chainsawrus.io.FileIO;

import android.opengl.GLES20;
import android.util.Log;

public class Shader {
	private int vShader;
	private int fShader;
	private int program;
	
	public Shader() {
		
	}
	
	public void loadProgram(String vSrc, String fSrc, FileIO fileIo) {
		vShader = loadShader(vSrc, GLES20.GL_VERTEX_SHADER, fileIo);
		fShader = loadShader(fSrc, GLES20.GL_FRAGMENT_SHADER, fileIo);
		int status[] = new int[1];
		
		program = GLES20.glCreateProgram();
		
		GLES20.glAttachShader(program, vShader);
		GLES20.glAttachShader(program, fShader);
		GLES20.glLinkProgram(program);
		
		GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, status, 0);
		
		if(status[0] == 0) {
			Log.d("GLES20 Program", GLES20.glGetProgramInfoLog(program));
			GLES20.glDeleteProgram(program);
		}
	}
	
	public int loadShader(String filename, int type, FileIO fileIO) {
		int shader = GLES20.glCreateShader(type);
		int status[] = new int[1]; 
		
		BufferedReader in = null;
		String shaderSrc = new String();
		try {
			in = new BufferedReader(new InputStreamReader(fileIO.readAsset(filename)));
			
			String line = new String();
			while((line = in.readLine()) != null) {
				shaderSrc += line;
			}
			if(in.readLine() == null) {
				in.close();
			}
		} catch(IOException e) {
			Log.e("GLES20 Debug", "Problems reading the Shader file!");
		}
		
		GLES20.glShaderSource(shader, shaderSrc);
		GLES20.glCompileShader(shader);
		
		GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, status, 0);
		
		if(status[0] == 0) {
			Log.e("GLES20 Debug", GLES20.glGetShaderInfoLog(shader));
			GLES20.glDeleteShader(shader);
			return 0;
		}
		return shader;
	}
	
	public int getProgram() {
		return program;
	}
}
